package captcha_logic

import (
	"fmt"
	"time"

	"gitee.com/Luna-CY/Golang-Project-Template/internal/context"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/errors"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/logger"
	gonanoid "github.com/matoous/go-nanoid"
)

// GenerateClickCaptcha 生成点击验证码
// 返回验证码的key，验证码答案图片，验证码主体图片，错误
func (cls *Captcha) GenerateClickCaptcha(ctx context.Context) (string, string, string, errors.Error) {
	var key = gonanoid.MustID(64)

	captcha, err := cls.captcha.Generate()
	if nil != err {
		logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("IGLCL_IC.C_HA.GCC_HA.174308 生成验证码数据失败: %v", err)

		return "", "", "", errors.ErrorServerInternalError("IGLCL_IC.C_HA.GCC_HA.194330", "生成验证码数据失败")
	}

	var data = captcha.GetData()
	if nil == data {
		logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("IGLCL_IC.C_HA.GCC_HA.234512 生成验证码数据失败，验证码数据为空")

		return "", "", "", errors.ErrorServerInternalError("IGLCL_IC.C_HA.GCC_HA.254525", "生成验证码数据失败")
	}

	master, err := captcha.GetMasterImage().ToBase64()
	if nil != err {
		logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("IGLCL_IC.C_HA.GCC_HA.304608 生成验证码数据失败，验证码主体图片获取失败: %v", err)

		return "", "", "", errors.ErrorServerInternalError("IGLCL_IC.C_HA.GCC_HA.324616", "生成验证码数据失败")
	}

	thumb, err := captcha.GetThumbImage().ToBase64()
	if nil != err {
		logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("IGLCL_IC.C_HA.GCC_HA.374644 生成验证码数据失败，验证码缩略图获取失败: %v", err)

		return "", "", "", errors.ErrorServerInternalError("IGLCL_IC.C_HA.GCC_HA.394650", "生成验证码数据失败")
	}

	if err := cls.cache.Set(ctx, fmt.Sprintf("captcha:%s", key), data, 5*time.Minute, true); nil != err {
		return "", "", "", err.Relation(errors.ErrorServerInternalError("IGLCL_IC.C_HA.GCC_HA.475144", "生成验证码数据失败"))
	}

	return key, thumb, master, nil
}
